package core.Resource
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import util.PathHelper;

	public class AniPackManager extends EventDispatcher
	{
		private var _aniPacks:Array;
		public function AniPackManager()
		{
			_aniPacks = [];
		}
		public static function get instance():AniPackManager
		{
			if(_instance == null)
				_instance = new AniPackManager();
			return _instance;
		}
		
		public function getAni(name:String):AniPack
		{
			var pack:AniPack;
			if(_aniPacks[name] !=null)
			{
				pack = _aniPacks[name] as AniPack;
				if(pack.state!=1)
				{
					pack.addEventListener(Event.COMPLETE,completeHandler);
				}
				else
				{
					this.dispatchEvent(new AniPackEvent(AniPackEvent.COMPLETE,pack));
				}
			}
			else
			{
				//TODO:如果没读完，先返一个默认样式
				pack = InstancePool.instance.getAniPack();
				pack.addEventListener(Event.COMPLETE,completeHandler);
				pack.load(name,PathHelper.getAniPath(name));
				_aniPacks[name] = pack;
			}
			return pack; 
		}
		
		public function clearAni(name:String):void
		{
			if(_aniPacks[name] !=null)
			{
				InstancePool.instance.setAniPack(_aniPacks[name]);
				delete _aniPacks[name];
			}
		}
		
		private function completeHandler(e:Event):void
		{
			var pack:AniPack = e.target as AniPack;
			pack.removeEventListener(Event.COMPLETE,completeHandler);
			this.dispatchEvent(new AniPackEvent(AniPackEvent.COMPLETE,pack));
		}
		
		private static var _instance:AniPackManager;
	}
}